// 导入其他的类
import Food from "./Food";
import ScorePanel from "./ScorePanel";
import Snake from "./Snake";
//游戏控制器，控制其他的类
class GameControl{
  // 食物类
  food:Food;
  // 积分牌类
  scorePanel:ScorePanel;
  // 蛇类
  snake:Snake;
  // 键盘方向
  direction:string = '';
  //蛇的存活状态
  isLive:boolean = true;
  constructor(){
    this.food = new Food();
    this.scorePanel = new ScorePanel(10,2);
    this.snake = new Snake();

    this.init();
    
  }

  init(){
    document.addEventListener('keydown',this.keydownHandler.bind(this))
    this.run();
  }
  
keydownHandler(e:KeyboardEvent){
//   ArrowUp
//  ArrowDown
//  ArrowLeft
//  ArrowRight
  this.direction = e.key;
}
run(){
  // 根据方向，来使蛇移动
/*     ArrowUp
       ArrowDown
       ArrowLeft
       ArrowRight */
      //  获取蛇现在的位置
    let X = this.snake.X;
    let Y = this.snake.Y;
    switch(this.direction){
      case 'ArrowUp':
      case 'Up':
        Y -= 10;
        break;
     case 'ArrowDown':
      case 'Down':
        Y +=10;
        break;
     case 'ArrowLeft':
      case 'Left':
        X -= 10;
        break;
     case 'ArrowRight':
      case 'Right':
        X += 10;
        break;

    }
    this.checkEat(X,Y);
    // 修改蛇的XY坐标
    try {
      this.snake.X = X;
      this.snake.Y = Y;
    } catch (e:any) {
      alert(e.message);
      this.isLive = false;
      this.initialization();
    }

    //开启定时调用
    this.isLive && setTimeout(this.run.bind(this),300 - (this.scorePanel.level - 1) * 30);
}
  //检查是否吃了食物
 checkEat(X:number,Y:number){
  if(X === this.food.X && Y === this.food.Y){
    this.food.change();
    this.scorePanel.addScore();
    this.snake.addBody();
  }

 }
 initialization(){
   this.snake.reSnake();
   this.direction = '';
   this.scorePanel.reScoreLevel();
    // console.log(this);
    
  this.isLive = true;
 }
}
export default GameControl;